﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;

namespace DianDian.Utils
{
    public class MusicUrlManage
    {
        /// <summary>
        /// 专门用来解析音乐地址的
        /// </summary>
        private static Windows.UI.Xaml.Controls.WebView webview;
        //private const string regString = "<location><![CDATA[(.+?)]]></location>";
        public static async Task<string> GetMusicUrl(API.Domain.Post post)
        {
            if (post.PlayerUrl.EndsWith(".swf"))
            {
                if (!string.IsNullOrEmpty(post.SongId))
                {
                    if (webview == null)
                    {
                        webview = new Windows.UI.Xaml.Controls.WebView();
                        System.Threading.Monitor.Enter(webview);
                        try
                        {
                            var task = new System.Threading.Tasks.TaskCompletionSource<object>();
                            webview.LoadCompleted += (s, e) =>
                            {
                                webview.InvokeScript("eval", new string[] { "function getMusicUrl(str){window.external.notify(sospa(str));}" });
                                task.SetResult(null);
                            };
                            var stream = await App.Current.GetApplicationStream("html.txt");
                            var txt = await Windows.Storage.FileIO.ReadTextAsync(stream);
                            webview.NavigateToString(txt);
                            await task.Task;
                        }
                        catch (Exception ex)
                        {
                            System.Threading.Monitor.Exit(webview);
                            throw new Exception("解析地址出现异常", ex);
                        }
                    }
                    string url = string.Format("http://data.xiami.com/widget/xml-single/uid/0/sid/{0}?from=xiami.com&biekaiqiang=IOS", post.SongId);
                    G.Net.HttpGet get = new G.Net.HttpGet(url);
                    var res = await get.RequestAsync();
                    if (res.Exception != null)
                        return null;
                    int startpos = res.Result.IndexOf("<location><![CDATA[");
                    int endpos = res.Result.IndexOf("]]></location>");
                    if (startpos == -1 || endpos == -1)
                        return null;
                    string address = res.Result.Substring(startpos+19, endpos - startpos-19);
                    System.Threading.Tasks.TaskCompletionSource<string> getMusicUrlTask = new System.Threading.Tasks.TaskCompletionSource<string>();
                    Windows.UI.Xaml.Controls.NotifyEventHandler handel = null;
                    handel = (s, e) =>
                    {
                        getMusicUrlTask.SetResult(e.Value);
                        webview.ScriptNotify -= handel;
                    };
                    webview.ScriptNotify += handel;
                    webview.InvokeScript("getMusicUrl", new string[] { address });
                    return await getMusicUrlTask.Task;
                    //web.InvokeScript("documentMouseDown", new string[] { "4h%2Fxit6F%82.t3Ffi.%22248mtA%3an2%4F54pp%2.meF242_53" });
                  
                }
                else
                    throw new Exception("无法解析音乐地址");
            }
            else
            {
                return post.PlayerUrl + "?m=1";
            }
        }
        /// <summary>
        /// 模拟IOS5发出请求的类
        /// </summary>
        private class IOS5Request : G.Net.HttpRequest
        {
            public IOS5Request(string str)
                : base(str)
            {
                base.Method = G.Net.HttpMethod.Get;
            }
            protected override void AppendHeaders(System.Net.Http.Headers.HttpRequestHeaders headers)
            {
                base.AppendHeaders(headers);
                headers.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3");
            }
        }
    }
}
